﻿using System.Web.Mvc;
using System.Web.Security;
using DMS.BO.Models;
using DMS.Business;

namespace DMS.BO.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/Login
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                //password ma hoa
                //var supplier = AccountService.ValidateLogin(model.UserName, TextUtility.Hash(model.Password));

                //password khong ma hoa
                var user = AccountService.ValidateLogin(model.UserName, model.Password);

                if (user != null)
                {

                    FormsAuthentication.SetAuthCookie(user.ID.ToString(), false);

                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ViewBag.Error = "Tên đăng nhập hoặc mật khẩu không chính xác";
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                var user = AccountService.ChangePassword(int.Parse(HttpContext.User.Identity.Name),model.OldPassword,model.NewPassword);

                if (user != null)
                {
                    ViewBag.Error = "Đổi mật khẩu thành công";
                }
                else
                {
                    ViewBag.Error = "Mật khẩu cũ không chính xác";
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }
    }
}